<?php
/**
 * Created by PhpStorm.
 * User: wuxiang
 * Date: 2016/8/30
 * Time: 14:18
 */

namespace Push\Controller;

use Api\Controller\PushInfoController;
use Common\Controller\AdminbaseController;
use Common\Libiary\BaseApiHttp;
use Common\Libiary\Uploadify;
use Common\Libiary\WechatMaterial;
use Api\Controller\PushInfo;
use Common\Libiary\LogEX;

class PushController extends AdminbaseController
{

    private $url;
    private $secret = '**9noww!@mwbyd&&';
    private $res;
    private $setUrl;
    public $result = [];
    const FANS_INDEX_KEY = 'oper:tags:cli:push';

    //发送列表
    function index()
    {
        $strarExpirationTime = I('strarExpirationTime', '', 'trim');
        $endExpirationTime = I('endExpirationTime', '', 'trim');

        $sql = '1=1';
        $sql .= $strarExpirationTime == '' ? '' : ' AND add_time > ' . strtotime($strarExpirationTime);
        $sql .= $endExpirationTime == '' ? '' : ' AND add_time < ' . strtotime($endExpirationTime);

        $push = M('WechatPush');
        $pushCount = $push->where($sql)->count();

        $Page = new \Think\Page($pushCount, 20, $_POST);

        $show = $Page->show();
        $arr = $push->where($sql)->order('add_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $material = M('WechatMaterial');
        foreach ($arr as $k => $v) {

            $mate = $material->where(['media_id' => $v['media_id']])->find();
            $arr[$k]['item'] = json_decode($mate['item'], true);

        }
        $this->assign('pager', $show);
        $this->assign('list', $arr);
        $this->assign('pushCount', $pushCount);
        $this->assign('strarExpirationTime', $strarExpirationTime);
        $this->assign('endExpirationTime', $endExpirationTime);
        $this->display();
    }

    function add()
    {

        $id = I('id', 1, 'intval');
        $wechat = new WechatMaterial();
        $this->result = $wechat->getTagsList();

        $tags = [];
        foreach ($this->result as $k => $v) {
            if ($v['total'] > 0) {

                $tags[$k]['cityid'] = $v['city'];
                $tags[$k]['name'] = $v['name'];
                $tags[$k]['total'] = $v['total'];
            }
        }
        $mate = M('WechatMaterial')->where(['id' => $id])->find();

        $mate['itemInfo'] = json_decode($mate['item'], true);

        $view = M('WechatView');
        $viewList = $view->select();
        $this->assign('viewList', $viewList);
        $this->assign('mate', $mate);

        $this->assign('tagInfo', $tags);

        $this->display();
    }


    //推送
    function addPush()
    {
        $actid = I('actid');
        $cityid = I('cityid');
        $media_id = I('media_id', '', 'trim');
        $timeInfo = I('timeInfo');

        $data['timestamp'] = time();
        $data['Type'] = 'mpnews';
        $data['mediaId'] = $media_id;
        $data['noticeId'] = $actid;  //活动id

        $push = M('WechatPush');
        //发送所有
        if (!$cityid) {
            $this->url = 'http://wx.push.mwee.cn/admin/weixin/sendall';  //正式环境
            if (TP_DEBUG) $this->url = 'http://wx.push.9now.net/admin/weixin/sendall'; //测试环境
            $mate = new WechatMaterial();
            $rest = $mate->post($this->url, json_encode($data));

            $result = json_decode($rest, true);
            if ($result['statusCode'] == 200) {
                $dataInfo['media_id'] = $media_id;
                $dataInfo['push_range'] = 0;
                $dataInfo['msg_id'] = $result['data']['msg_id'];
                $pk = $push->add($dataInfo);
                $sql = $push->getLastSql();
                LogEX::i('微信推送所有会员', ['sql' => $sql, 'dataInfo' => $dataInfo, 'data' => $rest, 'url' => $this->url], __FILE__, __LINE__);

            }
        } else {
            //按照标签（城市）来发
            $mateInfo = new WechatMaterial();
            //获取城市下粉丝总数
            $fansList = $mateInfo->getTotal($cityid);
            $fansTotal = 0;
            foreach ($fansList as $v) {
                $fansTotal += $v['total'];
            }

            LogEX::i('微信推送发送所有会员总数', ['data' => $fansTotal], __FILE__, __LINE__);

            //获取标签下粉丝列表
            //需要获取几次
            $offset = 1000;
            $page = ceil($fansTotal / $offset);
            $arr = [];
            //循环获取并发送
            for ($i = 1; $i <= $page; $i++) {

                LogEX::i('微信推送发送共有'.$i.$page, [], __FILE__, __LINE__);
                //获取粉丝
                $arr['city'] = $cityid;
                $arr['page'] =  $i;
                $arr['pageSize'] = $offset;
                $arr['media_id'] = $media_id;
                $arr['push_range'] = $cityid;
                $arr['noticeId'] = $actid ? $actid : 0;  //活动id
                LogEX::i('循环获取数据redis', ['data' => $arr], __FILE__, __LINE__);
                $this->set(self::FANS_INDEX_KEY, $arr);

            }
            echo 0;
            exit;
        }
    }

    function set($key, $val)
    {
        LogEX::i('循环获取数据redis', [$key, $val], __FILE__, __LINE__);
        $redis = new \Redis();
        $redis->connect(REDIS_PUSH_TAGS, REDIS_PUSH_TAGS_PORT);
        $redis->auth(REDIS_PUSH_TAGS_AUTH);
        $redis->lPush($key, json_encode($val));
        $redis->lPush($key.'22', json_encode($val));
    }

    function detail()
    {
        $id = I('id', '', 'intval');
        $push = M('WechatPush');
        $info = $push->where(['id' => $id])->find();

        $mateList = M('WechatMaterial');
        $mateInfo = $mateList->where(['media_id' => $info['media_id']])->find();

        $mateInfo['item'] = json_decode($mateInfo['item'], true);
        $data['push'] = $info;
        $data['mate'] = $mateInfo;

        $this->assign('data', $data);
        $this->display();
    }


}